from django.contrib import admin
from models import Photo, Owner, Note
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from utils import flickrapi as f_api, process_import
from garetjax import config
from decorators import require_flickr_auth
from django.utils.text import capfirst

class PhotoAdmin(admin.ModelAdmin):
    list_display = ('title', 'geo_location', 'date_taken', 'date_posted', 'date_update')
    def __call__(self, request, url):
        """Adds additional functionality to the admin class."""
        path = url or ""
        parts = path.strip("/").split("/")
        
        if len(parts) == 1 and parts[0] == "sync":
            return self.sync_view(request)
        elif len(parts) == 2 and parts[0] == "sync":
            return self.status_view(request)
        else:
            return super(PhotoAdmin, self).__call__(request, url)
    
    def status_view(self, request):
        return HttpResponse(config.get('flickr:imported'), mimetype="text/plain")
    
    @require_flickr_auth
    def sync_view(self, request):
        model = self.model
        opts = model._meta
        app_label = opts.app_label

        user_id = config.get('flickr:user_id')

        f = f_api()

        count = int(f.people_getInfo(user_id=user_id).find('person').find('photos').find('count').text)
        
        config.set('flickr:imported', 0)
        
        import threading
        t = threading.Thread(target=process_import, args=[f,count])
        t.setDaemon(True)
        t.start()

        return render_to_response('admin/flickr/sync_progress.html', {
            'total_count': count,
            'opts': opts,
            'app_label': app_label,
            'module_name': capfirst(opts.verbose_name),
            'title': 'Sincronizza con flickr',
        }, RequestContext(request))
        

admin.site.register(Photo, PhotoAdmin)
admin.site.register(Owner)
admin.site.register(Note)